package com.party.mobile.biz.activity;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.PartyCode;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.city.City;
import com.party.core.model.commune.CMemberInfo;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.distributor.DistributorDetail;
import com.party.core.model.distributor.DistributorDetailType;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.goods.GoodsCoupons;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.order.*;
import com.party.core.model.store.StoreGoods;
import com.party.core.model.thirdParty.ThirdParty;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.OrderActivityBizService;
import com.party.core.service.city.ICityService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.commune.impl.CIntegralBizService;
import com.party.core.service.commune.impl.CIntegralItemService;
import com.party.core.service.commune.impl.CUserIntegralService;
import com.party.core.service.copartner.IBrokerageItemService;
import com.party.core.service.count.IDataCountService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.member.util.MemberFormUtil;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderTradeService;
import com.party.core.service.store.IStoreGoodsService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.thirdParty.IThirdPartyService;
import com.party.mobile.biz.analyze.AnalyzeBizService;
import com.party.mobile.biz.analyze.MemberCopartnerDetailBizService;
import com.party.mobile.biz.analyze.MemberMerchantDetailBizService;
import com.party.mobile.biz.copartner.BrokerageBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.mobile.biz.member.CIntegralBizToService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.biz.order.MessageOrderBizService;
import com.party.mobile.biz.order.OrderBizService;
import com.party.mobile.biz.orderquery.QueryBizService;
import com.party.mobile.biz.refund.RefundBizService;
import com.party.mobile.jms.publisher.service.IOrderCancelPubulisherService;
import com.party.mobile.web.dto.activity.input.ApplyInput;
import com.party.mobile.web.dto.activity.output.ApplyOutput;
import com.party.mobile.web.dto.activity.output.BuyerOutput;
import com.party.mobile.web.dto.activity.output.RegisterCertificateOutput;
import com.party.mobile.web.dto.distributor.input.ApplyDistributorInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.order.Output.OrderOutput;
import com.party.mobile.web.dto.order.input.BookOrderInput;
import com.party.notify.notifyPush.officialPartner.IOfficialPartnerNotifySendService;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.party.pay.model.refund.AliPayRefundResponse;
import com.party.pay.model.refund.WechatPayRefundResponse;
import com.party.pay.service.pay.PayOrderBizService;
import com.party.pay.service.refund.RefundOrderBizService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 活动报名
 * party
 * Created by wei.li
 * on 2016/9/29 0029.
 */

@Service
public class MemberActBizService {

    @Autowired
    private PayOrderBizService payOrderBizService;

    @Autowired
    IMemberActService memberActService;

    @Autowired
    IStoreGoodsService storeGoodsService;

    @Autowired
    OrderBizService orderBizService;

    @Autowired
    IOrderFormService orderFormService;

    @Autowired
    CurrentUserBizService currentUserBizService;

    @Autowired
    IActivityService activityService;

    @Autowired
    IThirdPartyService thirdPartyService;

    @Autowired
    ICityService cityService;

    @Autowired
    IGoodsCouponsService goodsCouponsService;

    @Autowired
    IDataCountService dataCountService;

    @Autowired
    MessageOrderBizService messageOrderBizService;

    @Autowired
    QueryBizService queryBizService;

    @Autowired
    ICounterfoilService counterfoilService;

    @Autowired
    ICounterfoilBusinessService counterfoilBusinessService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private RefundBizService refundBizService;
    @Autowired
    private OrderActivityBizService orderActivityBizService;
    @Autowired
    private RefundOrderBizService refundOrderBizService;
    @Autowired
    private ActivityBizService activityBizService;
    @Autowired
    private CounterfoilBizService counterfoilBizService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private AnalyzeBizService analyzeBizService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IOrderCancelPubulisherService orderCancelPubulisherService;
    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private MemberMerchantDetailBizService memberMerchantDetailBizService;

    @Autowired
    private GatherProjectBizService gatherProjectBizService;

    @Autowired
    private DistributorBizService distributorBizService;
    @Autowired
    private BrokerageBizService brokerageBizService;
    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;
    @Autowired
    private IDistributorRelationService distributorRelationService;
    @Autowired
    private IDistributorDetailService distributorDetailService;
    @Autowired
    private IDistributorCountService distributorCountService;
    @Autowired
    private IBrokerageItemService brokerageItemService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private CIntegralBizToService integralBizToService;
    @Autowired
    private IOfficialPartnerNotifySendService officialPartnerNotifySendService;
    @Autowired
    private CIntegralItemService integralItemService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private CUserIntegralService userIntegralService;
    @Autowired
    private CIntegralBizService integralBizService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private ICMemberInfoService cMemberInfoService;

    protected static Logger logger = LoggerFactory.getLogger(MemberActBizService.class);

    /**
     * 插入活动报名
     *
     * @param memberAct 活动报名
     * @return 活动报名实体
     */
    public String insert(MemberAct memberAct) {
        String id = memberActService.insert(memberAct);

        return id;
    }

    /**
     * 活动报名
     *
     * @param input    输入视图
     * @param memberId 会员编号
     * @return 报名输出视图
     */
    @Transactional
    public ApplyOutput apply(ApplyInput input, String memberId) {
        //生成报名数据
        MemberAct memberAct = new MemberAct();
        memberAct.setActId(input.getId());
        memberAct.setMemberId(memberId);
        memberAct.setName(input.getRealname());
        memberAct.setMobile(input.getMobile());
        memberAct.setCompany(input.getCompany());
        memberAct.setJobTitle(input.getTitle());
        memberAct.setExtra(input.getExtra());
        memberAct.setWechatNum(input.getWechatNum());
        Activity activity = activityService.get(input.getId());
        memberAct.setPayment(activity.getPrice());
        memberAct.setUpdateBy(memberId);
        memberAct.setJoinin(YesNoStatus.YES.getCode());//报名
        memberAct.setCollect(YesNoStatus.YES.getCode());
        memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDITING.getCode());

        BaseModel.preByInfo(memberId, memberAct);
        String memberActId = this.insert(memberAct);

        //统计报名量
        int joinNum = orderFormService.calculateBuyNum(activity.getId(), null, false, OrderType.ORDER_ACTIVITY.getCode());
        activity.setJoinNum(joinNum);
        activityService.update(activity);

        ApplyOutput applyOutput = new ApplyOutput();
        applyOutput.setMemberActId(memberActId);
        applyOutput.setActStatus(memberAct.getCheckStatus());

        //机构用户关系
        partnerMemberService.insert(activity.getMemberId(), memberId);
        return applyOutput;
    }

    /**
     * 活动报名
     *
     * @param input    输入视图
     * @param memberId 会员编号
     * @return 报名输出视图
     */
    @Transactional
    public ApplyOutput apply2(ApplyInput input, String memberId) {
        // 生成订单数据
        BookOrderInput bookOrderInput = orderBizService.createBookOrder(input);
        OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);

        // 生成报名数据
        MemberAct memberAct = new MemberAct();
        memberAct.setActId(input.getId());
        memberAct.setMemberId(memberId);
        memberAct.setName(input.getRealname());
        memberAct.setMobile(input.getMobile());
        memberAct.setCompany(input.getCompany());
        memberAct.setJobTitle(input.getTitle());
        memberAct.setExtra(input.getExtra());
        memberAct.setWechatNum(input.getWechatNum());
        memberAct.setPayment(input.getPayment());
        memberAct.setUpdateBy(memberId);
        memberAct.setJoinin(YesNoStatus.YES.getCode());// 报名
        memberAct.setCollect(YesNoStatus.YES.getCode());
        // 审核状态已审核
        memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());

        // 将订单Id放入报名表
        memberAct.setOrderId(orderOutput.getId());

        BaseModel.preByInfo(memberId, memberAct);

        String memberActId = this.insert(memberAct);

        // 属于分享连接
        if (!Strings.isNullOrEmpty(input.getStoreGoodsId())) {
            // 统计成交量
            StoreGoods storeGoods = storeGoodsService.get(input.getStoreGoodsId());
            Integer num = storeGoods.getApplyNum();
            storeGoods.setApplyNum(num + 1);
            storeGoodsService.update(storeGoods);
        }
        ApplyOutput applyOutput = new ApplyOutput();
        applyOutput.setMemberActId(memberActId);
        applyOutput.setActStatus(memberAct.getCheckStatus());
        applyOutput.setOrderId(orderOutput.getId());

        return applyOutput;
    }

    /**
     * 活动报名
     *
     * @param input    输入视图
     * @param memberId 会员编号
     * @return 报名输出视图
     */
    @Transactional
    public ApplyOutput apply3(ApplyInput input, String memberId) {
        ApplyOutput applyOutput = new ApplyOutput();

        // 生成报名数据
        MemberAct memberAct = new MemberAct();
        memberAct.setActId(input.getId());
        memberAct.setMemberId(memberId);
        memberAct.setName(input.getRealname());
        memberAct.setMobile(input.getMobile());
        memberAct.setCompany(input.getCompany());
        memberAct.setJobTitle(input.getTitle());
        memberAct.setExtra(input.getExtra());
        memberAct.setWechatNum(input.getWechatNum());
        memberAct.setPayment(input.getPayment());
        memberAct.setCounterfoilName(input.getCounterName()); // 票据名称
        memberAct.setCounterfoilType(input.getCounterType()); // 票据类型
        memberAct.setUpdateBy(memberId);
        memberAct.setJoinin(YesNoStatus.YES.getCode());// 报名
        memberAct.setCollect(YesNoStatus.YES.getCode());
        memberAct.setPayStatus(MemberAct.PAY_STATUS_NO); // 没有付款
        // 审核状态已审核
        memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
        // 正常报名
        memberAct.setApplyFrom(MemberAct.APPLY_FROM_FRONT);
        BaseModel.preByInfo(memberId, memberAct);
        memberActService.insert(memberAct);

        // 0元活动不生成订单 线上支付才生成订单
        if (input.getCounterType().equals(CounterfoilType.TYPE_ON_LINE.getCode())) {
            // 生成订单数据
            BookOrderInput bookOrderInput = orderBizService.createBookOrder(input);
            OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
            // 将订单Id放入报名表
            memberAct.setOrderId(orderOutput.getId());
            memberActService.update(memberAct);
            applyOutput.setOrderId(orderOutput.getId());
        }

        // 属于分享连接
        if (!Strings.isNullOrEmpty(input.getStoreGoodsId())) {
            // 统计成交量
            StoreGoods storeGoods = storeGoodsService.get(input.getStoreGoodsId());
            Integer num = storeGoods.getApplyNum();
            storeGoods.setApplyNum(num + 1);
            storeGoodsService.update(storeGoods);
        }

        applyOutput.setMemberActId(memberAct.getId());
        applyOutput.setActStatus(memberAct.getCheckStatus());

        return applyOutput;
    }

    /**
     * 获取活动下单状态
     *
     * @param memberActId 活动报名id
     * @return 活动下单状态
     */
    @Transactional
    public Integer getActStatus(String memberActId) {
        Integer actStatus = ActStatus.ACT_STATUS_NO_JOIN.getCode();

        MemberAct dbMemberAct = memberActService.get(memberActId);


//        //获取活动参与状态
//        if (null != dbMemberAct) {
//            if (null == dbMemberAct.getJoinin() || 0 == dbMemberAct.getJoinin()) {
//                actStatus = ActStatus.ACT_STATUS_CANCEL.getCode();//已取消
//            } else {
//                if ("2".equals(dbMemberAct.getCheckStatus())) {
//                    actStatus = ActStatus.ACT_STATUS_AUDIT_REJECT.getCode();//审核未通过
//                } else {
//                    OrderFormController orderForm = orderFormService.get(dbMemberAct.getOrderId());
//
//                    if (null != orderForm) {
//                        if (orderForm.getStatus() == OrderStatus.ORDER_STATUS_IN_REVIEW.getCode())
//                            actStatus = ActStatus.ACT_STATUS_AUDITING.getCode();//审核中
//                        else if (orderForm.getStatus() == OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode())
//                            actStatus = ActStatus.ACT_STATUS_AUDIT_PASS.getCode();//审核通过，待付款
//                        else if (orderForm.getStatus() == OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())
//                            actStatus = ActStatus.ACT_STATUS_AUDIT_PASS.getCode();//已付款，报名成功
//                    }
//                }
//            }
//        }
        if (null != dbMemberAct)
            actStatus = dbMemberAct.getCheckStatus();

        return actStatus;
    }

    /**
     * 获取活动下单状态
     *
     * @param memberId   会员id
     * @param activityId 活动id
     * @return 获取活动下单状态
     */
    @Transactional
    public Integer getActStatus(String memberId, String activityId) {
        Integer actStatus = ActStatus.ACT_STATUS_NO_JOIN.getCode();

        MemberAct dbMemberAct = memberActService.getMyAct(memberId, activityId);

        if (null != dbMemberAct)
            actStatus = dbMemberAct.getCheckStatus();

        return actStatus;
    }

    /**
     * 取消活动报名
     *
     * @param memberActId 活动报名id
     * @return 报名输出视图
     */
    @Transactional
    public ApplyOutput joinCancel(String memberActId, HttpServletRequest request) throws BusinessException {
        ApplyOutput applyOutput = new ApplyOutput();

        MemberAct memberAct = memberActService.get(memberActId);
        if (null != memberAct) {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            //验证当前用户是否与报名用户为同一个人
            boolean validate = currentUser.getId().equals(memberAct.getMemberId());
            if (!validate) {
                throw new BusinessException(PartyCode.JOIN_ACT_MEMBER_ERROR, "取消订单，当前用户与报名用户不是同一个人");
            }

            // 等于空表示这是第一次报名，还未生成订单
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                //取消报名，修改订单状态为其它
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());

                if (null != orderForm) {
                    if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {
                        throw new BusinessException(PartyCode.ORDER_HAVE_PAID, "订单已支付，不能取消");
                    }
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                    orderFormService.update(orderForm);
                }
//            	else
//            	{
//            		throw new BusinessException(PartyCode.JOIN_ACT_MEMBERACT_ERROR, "取消报名失败，订单数据异常");
//            	}
            }

            memberAct.setJoinin(YesNoStatus.NO.getCode());//设置取消报名
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_CANCEL.getCode());//设置取消报名

            applyOutput.setMemberActId(memberAct.getId());
            applyOutput.setActStatus(memberAct.getCheckStatus());

            // 个人活动报名数量统计-1, 由于已经支付的不能取消, 所以只需要报名数量, 而不需要金额
            try {
                String partnerId = activityService.get(memberAct.getActId()).getMember();
//				memberPersonalCountBizService.updateActivityNum(partnerId, currentUser.getId(), false);
                PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(partnerId, currentUser.getId());
                memberPersonalCountBizService.countOne(partnerMember);
            } catch (Exception e) {
                logger.error("实时更新个人活动报名数量异常", e);
            }

            memberActService.update(memberAct);//更新报名信息
        } else {
            throw new BusinessException(PartyCode.JOIN_ACT_ORDER_ERROR, "取消报名失败，报名数据异常");
        }

        try {
            activityCancel(memberActId);
        } catch (Exception e) {
            logger.error("实时更新合伙人报名统计数异常");
        }

        return applyOutput;
    }

    @Transactional
    public void activityCancel(String memberActId) {
        try {
            String relationId = distributorBizService.activityCancelApply(memberActId);
            if (StringUtils.isNotEmpty(relationId)) {
                memberCopartnerDetailBizService.updateApplyNumSub(relationId, memberActId);
            }
        } catch (Exception e) {
            logger.error("活动退款，统计数据处理异常", e);
        }
    }

    /**
     * 活动报名凭证业务
     *
     * @param memberActId
     * @param request
     * @return
     * @throws BusinessException 活动报名凭证
     */
    @Transactional
    public RegisterCertificateOutput getRegisterCertification(String memberActId, HttpServletRequest request) throws BusinessException {
        RegisterCertificateOutput registerCertificateOutput = null;

        MemberAct memberAct = memberActService.get(memberActId);
        if (null != memberAct) {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            //验证当前用户是否与报名用户为同一个人
            boolean validate = currentUser.getId().equals(memberAct.getMemberId());
            if (!validate) {
                throw new BusinessException(PartyCode.JOIN_ACT_MEMBER_ERROR, "当前用户与报名用户不是同一个人");
            }

            if (!memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_PAID.getCode())) {
                throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "活动状态错误");
            }

            Activity activity = activityService.get(memberAct.getActId());
            //
            OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
            if (null != orderForm && null != activity) {
                registerCertificateOutput = RegisterCertificateOutput.transform(activity);
                //查询城市
                City city = cityService.get(activity.getCityId());
                registerCertificateOutput.setCityName(city.getName());

                //获取活动提供方
                ThirdParty thirdParty = thirdPartyService.get(activity.getThirdPartyId());

                registerCertificateOutput.setThirdPartyName(thirdParty.getComName());
                registerCertificateOutput.setPhone(thirdParty.getTelephone());

                //核销码
                GoodsCoupons goodsCoupons = new GoodsCoupons();
                goodsCoupons.setGoodsId(activity.getId());
                goodsCoupons.setMemberId(currentUser.getId());

                List<GoodsCoupons> goodsCouponseslist = goodsCouponsService.list(goodsCoupons);

                List<String> list = new ArrayList<>();
                for (int i = 0; i < goodsCouponseslist.size(); i++) {
                    list.add(goodsCouponseslist.get(i).getVerifyCode());
                }
                registerCertificateOutput.setConsumerCode(list);
            } else {
                throw new BusinessException(PartyCode.JOIN_ACT_ORDER_ERROR, "活动订单数据异常");
            }
        } else {
            throw new BusinessException(PartyCode.JOIN_ACT_MEMBERACT_ERROR, "报名数据异常");
        }

        return registerCertificateOutput;
    }

    /**
     * 取出报名数据返回前端
     *
     * @param memberId
     * @param applyInput
     * @return 报名数据
     */
    @Transactional
    public ApplyOutput getApplyData(String memberId, ApplyInput applyInput) throws BusinessException {
        MemberAct dbMemberAct = memberActService.getMyAct(memberId, applyInput.getId());
        ApplyOutput applyOutput = new ApplyOutput();
        if (null != dbMemberAct) {
            // 已经报名,取出报名信息
            if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                    || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                    || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "活动报名状态错误");
            }

            Activity activity = activityService.get(applyInput.getId()); // 对应活动
            if (StringUtils.isNotEmpty(dbMemberAct.getOrderId())) {
                OrderForm orderForm = orderFormService.get(dbMemberAct.getOrderId());
                if (orderForm != null) {
                    // 订单状态不等于已退款，更改状态
                    if (!orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                        orderForm.setLinkman(applyInput.getRealname());// 联系人
                        orderForm.setPhone(applyInput.getMobile());// 手机
                        float payment = activity.getPrice() * orderForm.getUnit(); // 金额
                        orderForm.setPayment(payment);
                        orderForm.setStatus(OrderStatus.ORDER_STATUS_IN_REVIEW.getCode()); // 更改为“审核中”状态
                        orderForm.setTitle(activity.getTitle());
                        orderFormService.update(orderForm);// 更新订单信息
                    }
                }
            }
            int joinNum = orderFormService.calculateBuyNum(activity.getId(), null, false, OrderType.ORDER_ACTIVITY.getCode());
            activity.setJoinNum(joinNum);
            activityService.update(activity);
            dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDITING.getCode()); // 更改为“审核中”状态
            dbMemberAct.setJoinin(YesNoStatus.YES.getCode());
            dbMemberAct.setName(applyInput.getRealname()); // 联系人
            dbMemberAct.setMobile(applyInput.getMobile()); // 手机
            dbMemberAct.setCompany(applyInput.getCompany()); // 公司名称
            dbMemberAct.setJobTitle(applyInput.getTitle()); // 公司职位
            dbMemberAct.setExtra(applyInput.getExtra()); // 备注信息
            dbMemberAct.setPayment(activity.getPrice()); // 活动费用
            dbMemberAct.setUpdateDate(new Date());
            dbMemberAct.setWechatNum(applyInput.getWechatNum());
            memberActService.update(dbMemberAct);// 更新报名信息

            applyOutput.setMemberActId(dbMemberAct.getId());
            applyOutput.setActStatus(dbMemberAct.getCheckStatus());
            applyOutput.setJoinNum(activity.getJoinNum());
        } else {
            // 没有报名，则新建报名信息
            applyOutput = apply(applyInput, memberId);
        }
        return applyOutput;
    }

    /**
     * 取出报名数据返回前端
     *
     * @param memberId
     * @param applyInput
     * @return 报名数据
     */
    @Transactional
    public ApplyOutput getApplyData2(String memberId, ApplyInput applyInput) throws BusinessException {
        MemberAct dbMemberAct = memberActService.getMyAct(memberId, applyInput.getId());
        Activity activity = activityService.get(applyInput.getId()); // 对应活动
        List<Counterfoil> counterfoils = counterfoilService.list(new Counterfoil(activity.getId(), Constant.BUSINESS_TYPE_ACTIVITY));
        String counterfoilId = "";
        for (Counterfoil c : counterfoils) {
            if (c.getPayment().equals(activity.getPrice())) {
                counterfoilId = c.getId();
                break;
            }
        }

        if (StringUtils.isNotEmpty(counterfoilId)) {
            Counterfoil counterfoil = counterfoilService.get(counterfoilId);
            applyInput.setCounterName(counterfoil.getName());
            applyInput.setPayment(counterfoil.getPayment());
        } else {
            applyInput.setPayment(activity.getPrice());
        }
        ApplyOutput applyOutput = new ApplyOutput();
        String memberActId = "";
        if (null != dbMemberAct) {
            memberActId = dbMemberAct.getId();
            // 已经报名,取出报名信息
            if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                    || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                    || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "该活动已报名过");
            }

            // 订单号存在，订单记录不存在
            if (StringUtils.isNotEmpty(dbMemberAct.getOrderId())) {
                OrderForm orderForm = orderFormService.get(dbMemberAct.getOrderId());
                if (orderForm != null) {
                    if (!orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                        Boolean flag = queryBizService.checkOrderTradeStatus(applyInput.getPayment(), orderForm);
                        if (flag == null || flag) {
                            // 订单状态等于已退款，重新生成订单数据
                            BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                            OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                            dbMemberAct.setOrderId(orderOutput.getId());
                            applyOutput.setOrderId(orderOutput.getId());
                        } else {
                            // 订单状态不等于已退款，更改状态
                            orderForm.setLinkman(applyInput.getRealname());// 联系人
                            orderForm.setPhone(applyInput.getMobile());// 手机
                            double payment = BigDecimalUtils.mul(applyInput.getPayment(), orderForm.getUnit()); // 金额
                            double payment2 = BigDecimalUtils.round(payment, 2);
                            orderForm.setPayment((float) payment2);
                            orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode()); // 更改为“待支付”状态
                            orderForm.setTitle(activity.getTitle());
                            orderFormService.update(orderForm);// 更新订单信息
                            applyOutput.setOrderId(orderForm.getId());
                        }
                    } else {
                        // 订单状态等于已退款，重新生成订单数据
                        BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                        OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                        dbMemberAct.setOrderId(orderOutput.getId());
                        applyOutput.setOrderId(orderOutput.getId());
                    }
                } else {
                    // 订单号存在，订单记录不存在 生成订单数据
                    BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                    OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                    dbMemberAct.setOrderId(orderOutput.getId());
                    applyOutput.setOrderId(orderOutput.getId());
                }
            }

            // 没有订单号
            if (StringUtils.isEmpty(dbMemberAct.getOrderId())) {
                // 生成订单数据
                BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                dbMemberAct.setOrderId(orderOutput.getId());
                applyOutput.setOrderId(orderOutput.getId());
            }
            dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode()); // 更改为“已审核”状态
            dbMemberAct.setJoinin(YesNoStatus.YES.getCode());
            dbMemberAct.setName(applyInput.getRealname()); // 联系人
            dbMemberAct.setMobile(applyInput.getMobile()); // 手机
            dbMemberAct.setCompany(applyInput.getCompany()); // 公司名称
            dbMemberAct.setJobTitle(applyInput.getTitle()); // 公司职位
            dbMemberAct.setExtra(applyInput.getExtra()); // 备注信息
            dbMemberAct.setPayment(applyInput.getPayment()); // 活动费用
            dbMemberAct.setCounterfoilName(applyInput.getCounterName()); // 票据名称
            dbMemberAct.setWechatNum(applyInput.getWechatNum()); // 微信号
            memberActService.update(dbMemberAct);// 更新报名信息

            applyOutput.setMemberActId(dbMemberAct.getId());
            applyOutput.setActStatus(dbMemberAct.getCheckStatus());
        } else {
            // 没有报名，则新建报名信息同时生成订单记录
            applyOutput = apply2(applyInput, memberId);
            memberActId = applyOutput.getMemberActId();
        }

        int joinNum = orderFormService.calculateBuyNum(activity.getId(), null, false, OrderType.ORDER_ACTIVITY.getCode());
        applyOutput.setJoinNum(joinNum);

        // 票据处理
        counterfoil(memberActId, counterfoilId, memberId);

        // 0元活动 自动报名成功
        if (applyInput.getPayment().equals(Float.valueOf("0.0"))) {
            try {
                orderBizService.updatePayBusiness(applyOutput.getOrderId(), applyInput.getFrom());
                messageOrderBizService.send(applyOutput.getOrderId());
            } catch (Exception e) {
                e.printStackTrace();
            }

            dbMemberAct = memberActService.getMyAct(memberId, applyInput.getId());
            applyOutput.setActStatus(dbMemberAct.getCheckStatus());
            applyOutput.setActId(activity.getId());
            applyOutput.setFrom(applyInput.getFrom());
        }
        return applyOutput;
    }

    @Transactional
    public ApplyOutput getApplyData4(String memberId, ApplyInput applyInput, GatherProject project, Counterfoil counterfoil) throws BusinessException {
        /**
         * 1、如果报名为收费，则再次报名生成新记录，对应新订单
         * 2、如果报名来自分销，则再次报名生成新记录，因为不能一条报名记录，对应多条分销关系
         * 3、如果报名为免费或者线下付费，则再次找之前生成的对应记录，没有则生成
         */
        applyInput.setPayment(counterfoil.getPayment());
        applyInput.setCounterName(counterfoil.getName());
        applyInput.setCounterType(counterfoil.getType());

        ApplyOutput applyOutput = new ApplyOutput();

        Activity activity = activityService.get(applyInput.getId());

        if (sysConfigService.isOpenExpirationRestriction()) {
            boolean isExpire = MemberFormUtil.isExpire(activity.getMember(), null);
            if (isExpire) {
                throw new BusinessException("该商户歇业中，无法报名");
            }
        }

        boolean isNew = true;

        if (CounterfoilType.TYPE_FREE.getCode().equals(counterfoil.getType())
                || CounterfoilType.TYPE_OFF_LINE.getCode().equals(counterfoil.getType())) {
            // 如果票据为免费或者为线下付费 没有记录则生成，有则更新
            MemberAct dbMemberAct = memberActService.getMyActFree(memberId, applyInput.getId(), counterfoil.getType());
            if (null == dbMemberAct) {
                applyOutput = insertApply4(memberId, applyInput, activity);
            } else {
                if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                    throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "该活动已报名过");
                }
                updateApply4(applyInput, counterfoil.getType(), applyOutput, dbMemberAct);

                isNew = false;
            }
        } else {
            MemberAct dbMemberAct = memberActService.getMyActNoFree(memberId, applyInput.getId());
            if (null == dbMemberAct) {
                applyOutput = insertApply4(memberId, applyInput, activity);
            } else {
                if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                        || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                    throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "该活动已报名过");
                }
                DistributorDetail detail = distributorDetailService.findByTargetId(dbMemberAct.getId());
                if (null != detail || CounterfoilType.TYPE_ON_LINE.getCode().equals(counterfoil.getType())) {
                    // 分销详情不为空，说明来自分销，需要生成新记录
                    // 如果为收费票据，需要生成新记录
                    applyOutput = apply3(applyInput, memberId);
                } else {
                    updateApply4(applyInput, counterfoil.getType(), applyOutput, dbMemberAct);

                    isNew = false;
                }
            }
        }

        if (null != project.getInfoItems()) {
            try {
                gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getGatherFormProjectId(), memberId, applyOutput.getMemberActId(), isNew);
            } catch (Exception e) {
                logger.error("保存自定义信息异常", e);
            }
        }

        if (null == applyInput.getDistributionType()) {
            applyInput.setDistributionType(DistributorRelationType.ACTIVITY.getCode());
        }

        String memberActId = applyOutput.getMemberActId();
        // 处理分销
        new Thread(() -> dealDistribution(applyInput, memberActId, memberId)).start();

        // 0元活动 自动报名成功 免费或者线下支付
        if (applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                applyInput.getCounterType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
            try {
                payOrderBizService.updatePayBusiness2(applyInput.getOrderType(), applyInput.getFrom(), applyInput.getId(), memberId, applyInput.getCounterfoilId());
                messageOrderBizService.sendFree(applyInput.getOrderType(), applyInput.getId(), applyOutput.getMemberActId(), memberId);
            } catch (Exception e) {
                logger.error("免费活动回调异常", e);
            }

            new Thread(() -> {
                if (OrderType.ORDER_ACTIVITY.getCode().equals(applyInput.getOrderType())) {
                    try {
                        memberMerchantDetailBizService.updateApplyNum(activity.getMember());
                    } catch (Exception e) {
                        logger.error("实时更新机构报名统计数异常", e);
                    }

                    // 只有免费活动才直接+1, 线下活动要手动点确认付款了才+1
                    if (applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode())) {
                        try {
                            PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(activity.getMember(), memberId);
                            memberPersonalCountBizService.countOne(partnerMember);
                        } catch (Exception e) {
                            logger.error("实时更新个人活动报名数量异常", e);
                        }
                    }
                }
            }).start();
            applyOutput.setActStatus(ActStatus.ACT_STATUS_PAID.getCode());
            applyOutput.setActId(applyInput.getId());
            applyOutput.setFrom(applyInput.getFrom());
        }

        //行知公社业务
        boolean isCommune = integralBizToService.isXZGSJurisdiction(activity.getMember());
        if (isCommune) {
            final String partnerId = activity.getMember();
            final String fmemberId = memberId;
/*            new Thread(() -> {*/
                //生成行知公社小程序二维码
                integralBizToService.generateXZGSXCXQRCode(partnerId, fmemberId);
/*            }).start();*/
/*            new Thread(() -> {*/
                //添加赠送积分
                try {
                    integralBizService.addGiftIntegral(partnerId, fmemberId);
                } catch (Exception e) {
                    logger.error("添加赠送积分异常", e.getMessage());
                }
/*            }).start();*/
        }

        // 票据处理
        Integer joinNum = counterfoil(applyOutput.getMemberActId(), applyInput.getCounterfoilId(), memberId);
        applyOutput.setJoinNum(joinNum);

        return applyOutput;
    }

    /**
     * 更新报名信息
     *
     * @param applyInput      报名信息
     * @param counterfoilType 票据类型
     * @param applyOutput     报名输出信息
     * @param dbMemberAct     报名记录
     * @return
     * @author yifeng
     * @date 9:45 2019/10/12
     **/
    private void updateApply4(ApplyInput applyInput, Integer counterfoilType, ApplyOutput applyOutput, MemberAct dbMemberAct) {
        dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode()); // 更改为“已审核”状态
        dbMemberAct.setJoinin(YesNoStatus.YES.getCode());
        dbMemberAct.setName(applyInput.getRealname()); // 联系人
        dbMemberAct.setMobile(applyInput.getMobile()); // 手机
        dbMemberAct.setCompany(applyInput.getCompany()); // 公司名称
        dbMemberAct.setJobTitle(applyInput.getTitle()); // 公司职位
        dbMemberAct.setExtra(applyInput.getExtra()); // 备注信息
        dbMemberAct.setPayment(applyInput.getPayment()); // 活动费用
        dbMemberAct.setCounterfoilName(applyInput.getCounterName()); // 票据名称
        dbMemberAct.setCounterfoilType(applyInput.getCounterType()); // 票据类型
        dbMemberAct.setWechatNum(applyInput.getWechatNum()); // 微信号
        dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_NO); // 没有付款
        dbMemberAct.setRemarks("");
        dbMemberAct.setCreateDate(new Date());
        dbMemberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        // 正常报名
        dbMemberAct.setApplyFrom(MemberAct.APPLY_FROM_FRONT);
        if (!CounterfoilType.TYPE_ON_LINE.getCode().equals(counterfoilType)) {
            dbMemberAct.setOrderId("");
        }
        memberActService.update(dbMemberAct);// 更新报名信息

        applyOutput.setMemberActId(dbMemberAct.getId());
        applyOutput.setActStatus(dbMemberAct.getCheckStatus());
        applyOutput.setOrderId(dbMemberAct.getOrderId());
    }

    /**
     * 新增报名记录
     *
     * @param memberId   用户id
     * @param applyInput 报名信息
     * @param activity   活动信息
     * @return
     * @author yifeng
     * @date 9:44 2019/10/12
     **/
    private ApplyOutput insertApply4(String memberId, ApplyInput applyInput, Activity activity) {
        ApplyOutput applyOutput;// 第一次报名
        applyOutput = apply3(applyInput, memberId);

        try {
            //机构用户关系
            PartnerMember partnerMember = new PartnerMember();
            partnerMember.setPartnerId(activity.getMember());
            partnerMember.setMemberId(memberId);

            PartnerMember pm = partnerMemberService.getSet(partnerMember);
            if (null != pm) {
                try {
                    officialPartnerNotifySendService.xzgsNewMemberNotify(memberId, activity.getMember(), partnerMember.getId());
                } catch (Exception e) {
                    logger.error("行知公社新会员加入消息通知异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("处理机构用户关系异常", e);
        }

        // 不是免费数据就个人统计表添加数据, 因为免费数据在下面实时更新个人活动报名数量的时候已经个人统计表添加数据
        if (!applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode())) {
            memberPersonalCountBizService.getSet(activity.getMember(), memberId);
        }
        return applyOutput;
    }

    /**
     * 报名处理分销
     *
     * @param applyInput  请求参数
     * @param memberActId 报名记录id
     * @param memberId    用户id
     */
    public void dealDistribution(ApplyInput applyInput, String memberActId, String memberId) {
        try {
            //分销统计
            DistributorRelation distributorRelation
                    = distributorRelationService.get(applyInput.getDistributionType(),
                    applyInput.getDistributorTargetId(), applyInput.getDistributorId());
            if (null != distributorRelation) {
                Integer findCount = 0;

                MemberAct query = new MemberAct();
                query.setMemberId(memberId);
                query.setActId(applyInput.getId());
                List<MemberAct> memberActs = memberActService.list(query);
                for (MemberAct item : memberActs) {
                    DistributorDetail applyDetail = distributorDetailService.get(item.getId()
                            , DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode(), distributorRelation.getId());
                    if (null != applyDetail) {
                        findCount++;
                        distributorDetailService.delete(applyDetail.getId());
                    }
                }

                DistributorDetail distributorDetail = new DistributorDetail();
                distributorDetail.setTargetId(memberActId);
                distributorDetail.setDistributorRelationId(distributorRelation.getId());
                distributorDetail.setType(DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode());
                distributorDetailService.insert(distributorDetail);

                // 如果已经保存分销详情，就不用再保存
                if (findCount == 0) {
                    distributorBizService.distributorCount(distributorRelation.getId(), DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode());

                    try {
                        memberCopartnerDetailBizService.updateApplyNum(memberActId);
                    } catch (Exception e) {
                        logger.error("实时更新合伙人报名统计数异常", e);
                    }
                }

                findCount = 0;
                for (MemberAct item : memberActs) {
                    List<BrokerageItem> brokerageItems = brokerageItemService.findByTargetId(item.getId());
                    if (null != brokerageItems && brokerageItems.size() > 0) {
                        for (BrokerageItem brokerageItem : brokerageItems) {
                            BrokerageItem t = new BrokerageItem();
                            t.setId(brokerageItem.getId());
                            t.setTargetId(memberActId);
                            brokerageItemService.update(t);
                        }
                        findCount++;
                        break;
                    }
                }

                // 免费的课程处理佣金
                try {
                    if (CounterfoilType.TYPE_FREE.getCode().equals(applyInput.getCounterType())
                            && OrderType.ORDER_COURSE.getCode().equals(applyInput.getOrderType())) {
                        if (findCount == 0) {
                            brokerageBizService.insertBrokerageItem(memberActId, applyInput.getId(), BrokerageItem.TYPE_COURSE, memberId);
                        }
                    }
                } catch (Exception e) {
                    logger.error("免费的课程处理佣金异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("报名的分销统计异常", e);
        }
    }

    /**
     * 取出报名数据返回前端
     *
     * @param memberId
     * @param applyInput
     * @return 报名数据
     */
    @Transactional
    public ApplyOutput getApplyData3(String memberId, ApplyInput applyInput, GatherProject project, Counterfoil counterfoil) throws BusinessException {
        Activity activity = activityService.get(applyInput.getId());

        applyInput.setPayment(counterfoil.getPayment());
        applyInput.setCounterName(counterfoil.getName());
        applyInput.setCounterType(counterfoil.getType());

        ApplyOutput applyOutput = new ApplyOutput();

        String memberActId;
        MemberAct dbMemberAct = memberActService.getMyAct(memberId, applyInput.getId());
        if (null != dbMemberAct) {
            memberActId = dbMemberAct.getId();
            // 已经报名,取出报名信息
            if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(dbMemberAct.getCheckStatus())
                    || ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(dbMemberAct.getCheckStatus())
                    || ActStatus.ACT_STATUS_PAID.getCode().equals(dbMemberAct.getCheckStatus())) {
                throw new BusinessException(PartyCode.JOIN_ACT_STATUS_ERROR, "该活动已报名过");
            }

            dbMemberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode()); // 更改为“已审核”状态
            dbMemberAct.setJoinin(YesNoStatus.YES.getCode());
            dbMemberAct.setName(applyInput.getRealname()); // 联系人
            dbMemberAct.setMobile(applyInput.getMobile()); // 手机
            dbMemberAct.setCompany(applyInput.getCompany()); // 公司名称
            dbMemberAct.setJobTitle(applyInput.getTitle()); // 公司职位
            dbMemberAct.setExtra(applyInput.getExtra()); // 备注信息
            dbMemberAct.setPayment(applyInput.getPayment()); // 活动费用
            dbMemberAct.setCounterfoilName(applyInput.getCounterName()); // 票据名称
            dbMemberAct.setCounterfoilType(applyInput.getCounterType()); // 票据类型
            dbMemberAct.setWechatNum(applyInput.getWechatNum()); // 微信号
            dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_NO); // 没有付款
            dbMemberAct.setRemarks("");
            dbMemberAct.setCreateDate(new Date());
            dbMemberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            memberActService.update(dbMemberAct);// 更新报名信息

            // 线上付款
            if (applyInput.getCounterType().equals(CounterfoilType.TYPE_ON_LINE.getCode())) {
                // 订单号存在，订单记录不存在
                if (StringUtils.isNotEmpty(dbMemberAct.getOrderId())) {
                    OrderForm orderForm = orderFormService.get(dbMemberAct.getOrderId());
                    if (orderForm != null) {
                        if (!orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                            Boolean flag = queryBizService.checkOrderTradeStatus(applyInput.getPayment(), orderForm);
                            if (flag == null || flag) {
                                // 订单状态等于已退款，重新生成订单数据
                                BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                                OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                                dbMemberAct.setOrderId(orderOutput.getId());
                                applyOutput.setOrderId(orderOutput.getId());
                            } else {
                                // 订单状态不等于已退款，更改状态
                                orderForm.setLinkman(applyInput.getRealname());// 联系人
                                orderForm.setPhone(applyInput.getMobile());// 手机
                                double payment = BigDecimalUtils.mul(applyInput.getPayment(), orderForm.getUnit()); // 金额
                                double payment2 = BigDecimalUtils.round(payment, 2);
                                orderForm.setPayment((float) payment2);
                                orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode()); // 更改为“待支付”状态
                                orderForm.setTitle(activity.getTitle());
                                orderForm.setUpdateDate(new Date());
                                orderFormService.update(orderForm);// 更新订单信息
                                applyOutput.setOrderId(orderForm.getId());
                            }
                        } else {
                            // 订单状态等于已退款，重新生成订单数据
                            BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                            OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                            dbMemberAct.setOrderId(orderOutput.getId());
                            applyOutput.setOrderId(orderOutput.getId());
                        }
                    } else {
                        // 订单号存在，订单记录不存在 生成订单数据
                        BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                        OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                        dbMemberAct.setOrderId(orderOutput.getId());
                        applyOutput.setOrderId(orderOutput.getId());
                    }
                }
                // 没有订单号
                if (StringUtils.isEmpty(dbMemberAct.getOrderId())) {
                    // 生成订单数据
                    BookOrderInput bookOrderInput = orderBizService.createBookOrder(applyInput);
                    OrderOutput orderOutput = orderBizService.bookActOrder(bookOrderInput, memberId);
                    dbMemberAct.setOrderId(orderOutput.getId());
                    applyOutput.setOrderId(orderOutput.getId());
                }

                memberActService.update(dbMemberAct);
            }

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("actId", applyInput.getId());
            params.put("counterfoilId", applyInput.getCounterfoilId());
            Integer joinNum = memberActService.getSuccessMemberAct(params);

            applyOutput.setMemberActId(dbMemberAct.getId());
            applyOutput.setActStatus(dbMemberAct.getCheckStatus());
            applyOutput.setJoinNum(joinNum);

            if (null != project.getInfoItems()) {
                gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getGatherFormProjectId(), memberId, memberActId, false);
            }
        } else {
            // 没有报名，则新建报名信息同时生成订单记录
            applyOutput = apply3(applyInput, memberId);
            memberActId = applyOutput.getMemberActId();

            try {
                //机构用户关系
                PartnerMember partnerMember = new PartnerMember();
                partnerMember.setPartnerId(activity.getMember());
                partnerMember.setMemberId(memberId);
                partnerMemberService.getSet(partnerMember);
            } catch (Exception e) {
                logger.error("处理机构用户关系异常", e);
            }

            // 不是免费数据就个人统计表添加数据, 因为免费数据在下面实时更新个人活动报名数量的时候已经个人统计表添加数据
            if (!applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode())) {
                memberPersonalCountBizService.getSet(activity.getMember(), memberId);
            }

            if (null != project.getInfoItems()) {
                gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getGatherFormProjectId(), memberId, memberActId, true);
            }

        }

        if (null == applyInput.getDistributionType()) {
            applyInput.setDistributionType(DistributorRelationType.ACTIVITY.getCode());
        }

        try {
            //分销统计
            DistributorRelation distributorRelation
                    = distributorRelationService.get(applyInput.getDistributionType(),
                    applyInput.getDistributorTargetId(), applyInput.getDistributorId());
            //如果存在分销关系
            if (null != distributorRelation) {
                ApplyDistributorInput applyDistributorInput = new ApplyDistributorInput();
                applyDistributorInput.setDistributorId(distributorRelation.getDistributorId());
                applyDistributorInput.setDistributorParentId(distributorRelation.getParentId());
                applyDistributorInput.setDistributorType(distributorRelation.getType());
                applyDistributorInput.setDistributorTargetId(distributorRelation.getTargetId());

                //统计报名
                applyDistributorInput.setTargetId(memberActId);
                applyDistributorInput.setType(DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode());
                boolean result = distributorBizService.setDistributorData(applyDistributorInput);
                if (result) {
                    try {
                        memberCopartnerDetailBizService.updateApplyNum(memberActId);
                    } catch (Exception e) {
                        logger.error("实时更新合伙人报名统计数异常", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("报名的分销统计异常", e);
        }

        // 票据处理
        counterfoil(memberActId, applyInput.getCounterfoilId(), memberId);

        // 0元活动 自动报名成功 免费或者线下支付
        if (applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                applyInput.getCounterType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
            try {
                payOrderBizService.updatePayBusiness2(applyInput.getOrderType(), applyInput.getFrom(), applyInput.getId(), memberId, applyInput.getCounterfoilId());
                messageOrderBizService.sendFree(applyInput.getOrderType(), applyInput.getId(), memberActId, memberId);
            } catch (Exception e) {
                logger.error("免费活动回调异常", e);
            }

            if (OrderType.ORDER_ACTIVITY.getCode().equals(applyInput.getOrderType())) {
                try {
                    memberMerchantDetailBizService.updateApplyNum(activity.getMember());
                } catch (Exception e) {
                    logger.error("实时更新机构报名统计数异常", e);
                }

                // 只有免费活动才直接+1, 线下活动要手动点确认付款了才+1
                if (applyInput.getCounterType().equals(CounterfoilType.TYPE_FREE.getCode())) {
                    try {
                        PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(activity.getMember(), memberId);
                        memberPersonalCountBizService.countOne(partnerMember);
                    } catch (Exception e) {
                        logger.error("实时更新个人活动报名数量异常", e);
                    }
                }
            }
            dbMemberAct = memberActService.get(memberActId);
            applyOutput.setActStatus(dbMemberAct.getCheckStatus());
            applyOutput.setActId(applyInput.getId());
            applyOutput.setFrom(applyInput.getFrom());
        }

        // 免费的课程处理佣金
        try {
            if (CounterfoilType.TYPE_FREE.getCode().equals(applyInput.getCounterType())
                    && OrderType.ORDER_COURSE.getCode().equals(applyInput.getOrderType())) {
                brokerageBizService.insertBrokerageItem(memberActId, activity.getId(), BrokerageItem.TYPE_COURSE, memberId);
            }
        } catch (Exception e) {
            logger.error("免费的课程处理佣金异常", e);
        }

        if (StringUtils.isNotEmpty(applyOutput.getOrderId())) {
//			orderCancelPubulisherService.send(applyOutput.getOrderId());
        }
        return applyOutput;
    }

    /**
     * 删除已有的票据，增加新的票据
     *
     * @param memberActId
     * @param counterfoilId
     * @param memberId
     */
    public Integer counterfoil(String memberActId, String counterfoilId, String memberId) {
        counterfoilBusinessService.deleteByBusinessId(memberActId);
        CounterfoilBusiness search = new CounterfoilBusiness(counterfoilId, memberActId);
        CounterfoilBusiness business = counterfoilBusinessService.getUnique(search);
        if (business == null) {
            search.setCreateBy(memberId);
            counterfoilBusinessService.insert(search);
        }

        Counterfoil counterfoil = counterfoilService.get(counterfoilId);
        counterfoil.setJoinNum(counterfoil.getJoinNum() + 1);
        counterfoilService.update(counterfoil);

        Activity activity = activityService.get(counterfoil.getBusinessId());
        activity.setJoinNum(activity.getJoinNum() + 1);
        activityService.update(activity);

        return activity.getJoinNum();
    }

    /**
     * 审核通过——免费
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @return
     */
    public boolean verifyPassFree(String memberActId, String activityId) {
        try {
            // 更改活动报名状态 待支付
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());

            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                // 更改订单状态 待支付
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    orderFormService.update(orderForm);
                } else {
                    memberAct.setOrderId("");
                }
            }
            memberActService.update(memberAct);

            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                payOrderBizService.updatePayBusiness(memberAct.getOrderId());
                messageOrderBizService.paySend(memberAct.getOrderId());
            } else {
                CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(memberActId);
                payOrderBizService.updatePayBusiness2(OrderType.ORDER_ACTIVITY.getCode(), null, activityId, memberAct.getMemberId(), counterfoilBusiness.getCounterfoilId());
                messageOrderBizService.sendFree(OrderType.ORDER_ACTIVITY.getCode(), activityId, memberActId, memberAct.getMemberId());
            }
            return true;
        } catch (Exception e) {
            logger.error("免费活动审核通过异常:{}", e);
            return false;
        }
    }

    /**
     * 审核通过——收费
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @return
     */
    public boolean verifyPassNoFree(String memberActId, String activityId) {
        try {
            Activity activity = activityService.get(activityId);
            // 更改活动报名状态 待支付
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                // 更改订单状态 待支付
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    // 如果订单状态等于已退款，则重新生成订单信息
                    if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_REFUND.getCode())) {
                        String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(), memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                        memberAct.setOrderId(orderId);
                    } else {
                        orderActivityBizService.updateActivityOrderStatus(memberAct.getOrderId(), OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    }
                } else {
                    String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(), memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                    memberAct.setOrderId(orderId);
                }
            } else {
                String orderId = orderActivityBizService.insertOrderForm(activity.getTitle(), memberAct, OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
                memberAct.setOrderId(orderId);
            }
            memberActService.update(memberAct);

            notifySendService.sendApplyPass(activity, memberAct.getId(), memberAct.getMobile(), memberAct.getMemberId(), ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
            return true;
        } catch (Exception e) {
            logger.error("收费活动审核通过异常:{}", e);
            return false;
        }
    }

    /**
     * 审核拒绝——免费
     */
    public boolean verifyFailFree(String memberActId, String activityId) {
        try {
            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);

            // 如果是线下活动, 拒绝的时候, 如果已经是设置为已付款了, 那钱也要减少
            if (memberAct.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode()) && MemberAct.PAY_STATUS_YES.equals(memberAct.getPayStatus())) {
                try {
                    String actId = memberAct.getActId();
                    Activity act = activityService.get(actId);
//					memberPersonalCountBizService.updateActivityNumMoney(act.getMember(), memberAct.getMemberId(), memberAct.getPayment(), false);
                    PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(act.getMember(), memberAct.getMemberId());
                    memberPersonalCountBizService.countOne(partnerMember);
                } catch (Exception e) {
                    logger.error("实时更新活动报名金额/数量异常 ", e);
                }
            }

            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                // 更改订单状态 其它
                OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
                if (orderForm != null) {
                    orderForm.setStatus(OrderStatus.ORDER_STATUS_OTHER.getCode());
                    orderFormService.update(orderForm);
                } else {
                    memberAct.setOrderId("");
                }
            }
            memberActService.update(memberAct);
            // 免费活动
            refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, null);
            messageOrderBizService.freeActivityRejectSend(memberActId, activityId, memberAct.getMemberId());
            return true;
        } catch (Exception e) {
            logger.error("免费活动审核拒绝异常:{}", e);
            return false;
        }
    }

    /**
     * 审核拒绝——收费
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean verifyFailNoFree(String memberActId) {
        try {
            // 更改活动报名状态 已拒绝
            MemberAct memberAct = memberActService.get(memberActId);
            memberAct.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
            memberAct.setPayStatus(MemberAct.PAY_STATUS_NO);
            memberActService.update(memberAct);

            OrderForm orderForm = orderFormService.get(memberAct.getOrderId());
            if (StringUtils.isEmpty(memberAct.getOrderId()) || orderForm == null) {
                refundOrderBizService.freeActivityReject(memberAct.getOrderId(), memberActId, null);
                messageOrderBizService.freeActivityRejectSend(memberActId, memberAct.getActId(), memberAct.getMemberId());
                return true;
            } else {
                // 更改订单状态 其它
                if (orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_HAVE_PAID.getCode())) {
                    Object responseData = refundBizService.refund(orderForm.getId());
                    if (responseData != null) {
                        if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {
                            AliPayRefundResponse response = (AliPayRefundResponse) responseData;
                            // 状态码等于10000表示成功
                            if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                                return refundBizService.activityRefundCallback(orderForm.getId(), response, PaymentWay.ALI_PAY.getCode());
                            }
                        } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
                            WechatPayRefundResponse response = (WechatPayRefundResponse) responseData;
                            // 退款成功
                            if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode()) && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                                return refundBizService.activityRefundCallback(orderForm.getId(), response, PaymentWay.WECHAT_PAY.getCode());
                            }
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("收费活动审核拒绝异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * 取消报名后的信息
     *
     * @param memberActId
     * @param applyOutput
     * @return
     */
    public Map<String, Object> getCancelInfo(String memberActId, ApplyOutput applyOutput) {
        Map<String, Object> map = Maps.newHashMap();
        MemberAct memberAct = memberActService.get(memberActId);
        List<Counterfoil> counterfoils = counterfoilBizService.getActivityCounterfoils(memberAct.getActId());
        Activity activity = activityService.get(memberAct.getActId());
        if (counterfoils.size() == 0) {
            activity = orderActivityBizService.updateActivityInfo(activity.getId());
        }
        map.put("limitNum", activity.getLimitNum());
        map.put("joinNum", activity.getJoinNum());
        map.put("counterfoils", counterfoils);
        map.put("actStatus", applyOutput.getActStatus());
        //如果不隐藏报名者
        if (activity.getJoinHidden().equals(YesNoStatus.NO.getCode())) {
            List<BuyerOutput> buyerOutputList = Lists.newArrayList();
            int buyerNum = activityBizService.getBuyer(activity.getId(), buyerOutputList);
            map.put("buyerOutputList", buyerOutputList);
            map.put("buyerNum", buyerNum);
        }
        return map;
    }

    public void testPayReset(String orderId) {
        OrderForm orderForm = orderFormService.get(orderId);
        orderForm.setStatus(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode());
        orderFormService.update(orderForm);

        OrderTrade orderTrade = orderTradeService.findByOrderId(orderId);
        if (null != orderTrade) {
            orderTradeService.delete(orderTrade.getId());
        }
        MemberAct memberAct = memberActService.findByOrderId(orderId);
        memberAct.setCheckStatus(1);
        memberActService.update(memberAct);

    }
}
